import os
from os.path import join

import bpy
from bpy.types import Operator

from .asset_utils import AssetUtils


class LoadAsset(Operator, AssetUtils):
    bl_idname = 'asset.render_master_load_asset'
    bl_label = '加载资产'

    @classmethod
    def poll(cls, context):
        return True

    def execute(self, context: 'bpy.context'):
        self.clear_all_asset()
        self.load_main(context)
        return {'FINISHED'}

    def load_main(self, context):
        path = self.pref.asset_root_path

        if not os.path.isdir(path):
            self.report({'ERROR'}, f"所设置的路径不是一个文件夹:{path}")
            return

        path, folder, file = self.walk(path)

        for fol in folder:
            if fol in self.asset_category:
                category = self.asset_category[fol].upper()  # 大写分类
                self.load_asset_category(join(path, fol), category)

    def load_asset_category(self, path, category):
        """加载资产分类"""
        for item in os.walk(path):
            path, folders, files = item
            self.asset_tree_pointer_.add(path, category, bool(folders))
            self.asset_items_pointer_.add(path, files, category)


class ClearAsset(Operator, AssetUtils):
    bl_idname = 'asset.render_master_clear_asset'
    bl_label = '清理资产'

    @classmethod
    def poll(cls, context):
        return True

    def execute(self, context: 'bpy.context'):
        self.clear_all_asset()
        return {'FINISHED'}


class RefreshAsset(Operator, AssetUtils):
    """#TODO
    """
    bl_idname = 'asset.render_master_refresh_asset'
    bl_label = '刷新资产'

    def execute(self, context: 'bpy.context'):
        return {'FINISHED'}


class RefreshIcon(Operator, AssetUtils):
    bl_idname = 'asset.render_master_refresh_icon'
    bl_label = '刷新图标'

    def execute(self, context: 'bpy.context'):
        return {'FINISHED'}


class ImportAsset(Operator, AssetUtils):
    """
    导入资产
    如果选择预览导入将会直接导入到预览集合中
    再点一次才会完全导入到场景中
    """
    bl_idname = 'asset.render_master_import_asset'
    bl_label = '导入资产'
    bl_options = {'UNDO', }

    def execute(self, context: 'bpy.context'):
        self.import_asset(context)
        return {'FINISHED'}


class ExportAsset(Operator, AssetUtils):
    """TODO 将当前项导出为资产
    """
    bl_idname = 'asset.render_master_export_asset'
    bl_label = '导出资产'

    def execute(self, context: 'bpy.context'):
        print(self, context)
        return {'FINISHED'}


class_tuple = (
    LoadAsset,
    RefreshAsset,
    RefreshIcon,
    ClearAsset,
    ImportAsset,
    ExportAsset,

)
reg_class, unreg_class = bpy.utils.register_classes_factory(class_tuple)


def register():
    reg_class()


def unregister():
    unreg_class()
